<template>
  <div style="padding:20px;">
    <div style="margin-bottom: 20px">
      <el-button class="filter-item" size="medium" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate">添加授权</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row >
      <el-table-column label="开始时间">
        <template slot-scope="scope">
          <span>{{ scope.row.startTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间">
        <template slot-scope="scope">
          <span>{{ scope.row.endTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusColor" size="mini">{{ scope.row.status | statusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请时间">
        <template slot-scope="scope">
          <span>{{ scope.row.applyTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="通过时间">
        <template slot-scope="scope">
          <span>{{ scope.row.approvalTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="list.length > 0" class="pagination-container">
      <el-pagination :current-page="listQuery.currentPage" :page-sizes="[10,25,50,100]" :page-size="listQuery.pageSize" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>
    <!--钥匙表单-->
    <el-dialog :visible.sync="dialogFormVisible" title="添加授权" center width="40%">
      <el-form ref="dataForm" :label-width="formLabelWidth" :rules="rules" :model="form">
        <el-form-item label="生效时段" prop="duration">
          <el-date-picker
            v-model="form.startTime"
            :default-value="currentTime"
            type="datetime"
            value-format="timestamp"
            placeholder="开始时间"/>
          ~
          <el-date-picker
            v-model="form.endTime"
            :default-value="form.startTime"
            type="datetime"
            value-format="timestamp"
            placeholder="结束时间"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <back-to-top :custom-style="myBackToTopStyle" :visibility-height="10" :back-position="0" transition-name="fade"/>
  </div>
</template>

<script>
import { getKey, addKey } from '@/api/device'
import BackToTop from '@/components/BackToTop'
export default {
  name: 'PassPane',
  components: { BackToTop },
  filters: {
    statusColor(status) {
      const statusMap = {
        0: 'warning',
        1: 'success',
        2: 'danger',
        3: 'info'
      }
      return statusMap[status]
    },
    statusFilter(status) {
      const statusMap = {
        0: '待审核',
        1: '通过',
        2: '未通过',
        3: '已下载'
      }
      return statusMap[status]
    }
  },
  data() {
    /* 校验生效时段 */
    const validateDuration = (rule, value, callback) => {
      if (!this.form.startTime) {
        callback(new Error('请选择开始时间'))
      } else if (!this.form.endTime) {
        callback(new Error('请选择结束时间'))
      } else {
        callback()
      }
    }
    return {
      currentTime: new Date().getTime(),
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        currentPage: 1,
        pageSize: 25,
        serialNumber: this.$route.params['sn']
      },
      dialogFormVisible: false,
      form: { /* 添加离线授权 */
        id: this.$route.params['id'],
        serialNumber: this.$route.params['sn'],
        startTime: null,
        endTime: null
      },
      rules: {
        duration: [{ validator: validateDuration, trigger: 'change' }]
      },
      formLabelWidth: '100px',
      myBackToTopStyle: {
        right: '50px',
        bottom: '50px',
        width: '40px',
        height: '40px',
        'border-radius': '4px',
        'line-height': '45px',
        background: '#e7eaf1'
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    /* 获取密码列表 */
    fetchData() {
      this.listLoading = true
      getKey(this.listQuery).then(response => {
        if (response.data) {
          this.list = response.data
          this.total = response.total
        }
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.currentPage = 1
      this.fetchData()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.currentPage = val
      this.fetchData()
    },
    resetForm() {
      this.form = {
        id: this.$route.params['id'],
        serialNumber: this.$route.params['sn'],
        startTime: null,
        endTime: null
      }
    },
    /* 添加离线授权 */
    handleCreate() {
      this.resetForm()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /* 提交离线授权表单 */
    submitForm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addKey(this.form).then(() => {
            this.actiniaSucc('添加授权成功')
            this.dialogFormVisible = false
            this.fetchData()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style scoped>
  .lonely {
    margin-left: 42px;
  }
</style>
